import { defineStore } from 'pinia'
import service from '@/utils/request'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: JSON.parse(localStorage.getItem('user')) || null,
    sessionId: localStorage.getItem('sessionId') || null
  }),
  
  getters: {
    isAuthenticated: (state) => !!state.user,
    id: (state) => state.user?.id || null,
    departmentId: (state) => state.user?.departmentId || null,
    userType: (state) => state.user?.userType || null,
    realName: (state) => state.user?.realName || ''
  },
  
  actions: {
    async login(credentials) {
      try {
        const response = await service.post('/user/login', credentials)
        
        if (!response || !response.sessionId || !response.user) {
          throw new Error('无效的登录响应格式')
        }
        
        this.sessionId = response.sessionId
        this.user = response.user
        
        localStorage.setItem('sessionId', this.sessionId)
        localStorage.setItem('user', JSON.stringify(this.user))
        
        return this.user
        
      } catch (error) {
        console.error('登录失败:', error)
        this.clearUser()
        throw error
      }
    },
    
    clearUser() {
      this.user = null
      this.sessionId = null
      localStorage.removeItem('sessionId')
      localStorage.removeItem('user')
    },
    
    // 新增方法：检查并获取当前用户
    ensureAuthenticated() {
      if (!this.isAuthenticated) {
        throw new Error('用户未登录')
      }
      return this.user
    }
  }
})